package com.hp.bon.sgw.wh.processor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hp.bon.sgw.wh.util.DateUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.convert.Xml2AVPConvetor;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.ChannelServer;
import com.hp.bon.sgw.core.InprogressMessageQueue;
import com.hp.bon.sgw.core.processor.Processor;
import com.hp.bon.sgw.core.route.RouteInfo;
import com.hp.bon.sgw.domain.ConvMapInfo;
import com.hp.bon.sgw.service.ConfigService;
import com.hp.bon.sgw.util.Comutils;
import com.hp.bon.sgw.util.dcc.DccAvpHelper;
import com.hp.bon.sgw.wh.service.LimitConfigService;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.service.UserResourceDetailConfigService;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_UTF8String;
import com.hp.ocs.diameter.message.AVP_Unsigned32;
import com.hp.ocs.diameter.message.Message;
import com.hp.ocs.diameter.message.MessageDictionary;

public class UserResourceDetailDccProcessor extends Processor{
	
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(UserResourceDetailDccProcessor.class);
	
	private long time=1000L;
	
	private static HashMap<String, Integer> countMap = new HashMap<String, Integer>();
	
	private UserResourceDetailConfigService userResourceDetailConfigService ;
	private UserResourceConfigService userResourceConfigService ;
	private static final int WEBSERVICER = 1;
	private static String PRODUCT_OFFER_INSTANCE_ID = "";
    private static String QUERY_FLAG = "";
    private JSONObject jsonObject =new JSONObject();
  //增加开关配置，jf3_flag=1，当该值配置为1，则表示不走鉴权，直接全部调用云平台； jf3_flag=0，则还是按目前流程走；
    private static	String jf3_flag="";
	public UserResourceDetailConfigService getUserResourceDetailConfigService() {
		return userResourceDetailConfigService;
	}

	public void setUserResourceDetailConfigService(
			UserResourceDetailConfigService userResourceDetailConfigService) {
		this.userResourceDetailConfigService = userResourceDetailConfigService;
	}

	public void shutdown() {
		dccProcessor.interrupt();
	}
	DccProcessor dccProcessor;
	public void init(){
		
		dccProcessor=new DccProcessor();
		dccProcessor.start();
	}
	
	class DccProcessor extends Thread{

		@Override
		public void run() {
			while (true) {
				try {
					time=userResourceDetailConfigService.getLongValue("limit_config_time", 1000L);
					countMap.clear();
					sleep(time);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}
		
	}
	
	public  synchronized Integer putValue(String key) {
		Integer i =countMap.get(key);
		logger.info("asd:"+i);
		if (i==null) {
			countMap.put(key, 1);
			i = 1;
		}else{
			i++;
			countMap.put(key,i);
		}
		return i;
	}
	
	
	
	private CallParam sendReqMsg(CallParam callParam ,String data ,String sendCount ,String sci)	{
		logger.info("===========333333333333===============" );
		
		String sessionId2 = callParam.getSessionId()+"B";
		XmlMessage req = new XmlMessage(true);
		req.setDATA(data);
		try {
			req.setDataElement(Comutils.parseText(data).getRootElement());
		} catch (Exception e) {
			e.printStackTrace();
		}
		req.setMID(sessionId2);
		req.setUID(callParam.getUserName());
		req.setSCID(sci);
		CallParam newCallParam = new CallParam(sessionId2, sci, req, callParam.getUserName(), callParam.getAsynHandler());
		newCallParam.setBussinessCallId(callParam.getBussinessCallId());
		newCallParam.setFromNode(callParam.getFromNode());
		newCallParam.setProcessor(this);
		RouteInfo r = ChannelServer.findRoute(newCallParam.getServiceContextId());
		int ret = 0;
		String errMsg = null;
		if (r == null) {
			errMsg = "No Route for " + newCallParam.getServiceContextId();
			ret = 3002;// 没有查到路由
		} else if (r.result != 0) {
			errMsg = "Route unavailable for " + newCallParam.getServiceContextId();
			ret = r.result;
		}
		if (ret != 0) {
			newCallParam.setRetCode(3002);
			newCallParam.setResultMsg(errMsg);
			callParam.getAsynHandler().onCallResult(newCallParam);
			return newCallParam;
		}
		newCallParam.setToNode(r.curNode);
		InprogressMessageQueue.getInstance().addRequest(newCallParam);
		r.curNode.getChannel().sendRequest(newCallParam);
		return newCallParam;
	}
	
	public CallParam parseResponse(CallParam callParam) {
		logger.info("===========444444444444===============" );
		Message request = (Message) callParam.getRecvResponse();
		Message answer = new Message();
		answer.prepareResponse(request);

		String sessionId = callParam.getSessionId();
		sessionId = sessionId.substring(0,sessionId.length()-2);
		request.updateAVP_UTF8String("263", sessionId);
		CallParam newcallParam = changeAVPTOXMl(callParam, request, sessionId);
		return newcallParam;
	}
	private CallParam changeAVPTOXMl(CallParam callParam, Message request,String sessionId) {
		CallParam newcallParam = new CallParam(sessionId, callParam.getServiceContextId(), request, callParam.getUserName(), callParam.getAsynHandler());
		XmlMessage ack = new XmlMessage(false);
		XmlMessage message = (XmlMessage)callParam.getRequest();
		Message messageRequset = (Message)newcallParam.getRequest();
		ack.setMID(message.getMID());
		ack.setREPTAG(0);
		ack.setSIG(null);
		ack.setRC("0");
		ack.setDS("SUCCESS");
		ack.setDATA(request.getDictionary().toString());
		newcallParam.setRecvResponse(callParam.getRecvResponse());
		newcallParam.setRequest(callParam.getRequest());
		ack = BuzProcessorManager.getInstance().convertMessageToAck(newcallParam);
		newcallParam.setRequest(messageRequset);
		newcallParam.setFromNode(callParam.getFromNode());
		newcallParam.setRecvResponse(ack);
		newcallParam.setResponse(null);
		return newcallParam;
	}
	public CallParam parseResponse1(CallParam callParam) {
		logger.info("===========555555555555===============" );
//		((Message)callParam.getSendRequest()).getDictionary().parseToString()
		
		if(callParam.getRecvResponse()==null){
			Message request =(Message)callParam.getSendRequest();
			callParam.setRequest(request);
			Message answer = new Message();
			answer.prepareResponse(request);
			MessageDictionary md = request.getDictionary();
			md.prepareResponseAVP(answer);
			
			
			Iterator<AVP> it = answer.iterator(Constants.DIAMETER_AVP_ORIGIN_HOST);
			while (it.hasNext()) it.remove();
			it = answer.iterator(Constants.DIAMETER_AVP_ORIGIN_REALM);
			while (it.hasNext()) it.remove();
			it = answer.iterator(263);
			while (it.hasNext()) it.remove();
			
			answer.add(new AVP_UTF8String(Constants.DIAMETER_AVP_ORIGIN_HOST,ConfigService.sgwHostId));
			answer.add(new AVP_UTF8String(Constants.DIAMETER_AVP_ORIGIN_REALM, ConfigService.realm));
			
			String sessionId = callParam.getSessionId();
			if(callParam.getServiceContextId().equals("RatableAuth.HSS@027.ctnbc-bon.net")){
				sessionId = sessionId.substring(0,sessionId.length()-1);
			}else if (callParam.getServiceContextId().equals("UserResourceQueryDetail.HWWH@027.ctnbc-bon.net")
					|| callParam.getServiceContextId().equals("UserResourceQueryDetail.HWHB@027.ctnbc-bon.net")
					|| callParam.getServiceContextId().equals("UserResourceQueryDetail.Balance@027.ctnbc-bon.net")) {
				sessionId = sessionId.substring(0,sessionId.length()-2);
			}
			
			answer.add(new AVP_UTF8String(263, sessionId));
			int serviceResultCode = callParam.getRetCode();
			int resultCode = serviceResultCode > 10000 ? 2001 : serviceResultCode;
		    if(serviceResultCode== UserResourceConfigService.getIntValue("DIAMETER_RESULT_TOO_BUSY", 501)||serviceResultCode==LimitConfigService.getIntValue("DIAMETER_RESULT_TOO_BUSY", 501)){
			     resultCode = 2001;
			}
		    answer.add(new AVP_Unsigned32(268, resultCode));
		    answer.add(DccAvpHelper.genDefaultServiceResultAVP(serviceResultCode));
			
		    callParam.setResponse(answer);
		    callParam.setRetCode(callParam.getRetCode());
		    callParam.setResultMsg(callParam.getResultMsg());
		}
		
		return callParam;
	}
	
	
	/**
	 * 
	 * @ 说     明：通过AVPCODE删除AVP，返回对应的删除索引位置	 
	 * @param：newMessage  Message
	 * @param：_AvpCode  int
	 * @return：返回对应的删除索引位置  0：无此AVP
	 */
	public static int removeAvpByAvpCode(Message newMessage,int _AvpCode){
		int _ind_removeAvp = -1;
		_ind_removeAvp  = newMessage.findFirst(_AvpCode);
		if( -1 != _ind_removeAvp){
			newMessage.remove(_ind_removeAvp);
		}
		return _ind_removeAvp;
	}
	
	public int endProcess(CallParam callParam) {
		logger.info("===========666666666666666===============" );
		logger.info("callParam.getRetCode():"+callParam.getRetCode());
		if(callParam.getRetCode()!=Constants.DIAMETER_SERVICE_RESULT_SUCCESS){
			if(callParam.getRetCode()==userResourceDetailConfigService.getIntValue("DIAMETER_RESULT_TOO_BUSY", 2005)){
				callParam.getAsynHandler().onCallResult(callParam);
				return 0 ;
			}else{
				callParam.getAsynHandler().onCallResult(parseResponse1(callParam));
				return 0 ;
			}
		}
		XmlMessage request = (XmlMessage) callParam.getRequest();
		String data = request.getDATA();
		String accNbr="" ,billingCycle="" ,destinationAttr="";

		Document doc = null;
		try {
			doc = DocumentHelper.parseText(data);
			Element root = doc.getRootElement();
			
			org.dom4j.Node node = root.selectSingleNode("//Service_Information/Bill_Information/Acc_Nbr");
			if (node != null) {
				accNbr = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/Billing_Cycle");
			if (node != null) {
				billingCycle = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/DestinationAttr");
			if (node != null) {
				destinationAttr = node.getStringValue();
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		int webService = userResourceDetailConfigService.getIntValue("IS_WEBSERVICE", 0);
		StringBuilder sb = new StringBuilder();
		String sci = callParam.getServiceContextId();

		Map<String, ConvMapInfo> allAVPMap = Xml2AVPConvetor.getInstance().getALLNamesMap();
		Message RatableAuthResponse = (Message) callParam.getRecvResponse();
		String isHbFlag = DccAvpHelper.getAVPValue(RatableAuthResponse, "Service_Information/Auth_Group/is_hb_flag", allAVPMap);
		isHbFlag = isHbFlag == null ? "" : isHbFlag;
		String homeAreaCode = DccAvpHelper.getAVPValue(RatableAuthResponse, "Service_Information/Auth_Group/HomeAreaCode", allAVPMap);
		homeAreaCode = homeAreaCode == null ? "" : homeAreaCode;
		if(webService == WEBSERVICER && isHbFlag.equals("1")) {
			getWebServiceCCR(accNbr, billingCycle, destinationAttr, sb);
		}
		else {
			getDCC(accNbr, billingCycle, destinationAttr, sb);
		}
		if("".equals(isHbFlag) || "".equals(homeAreaCode)){
			callParam.getAsynHandler().onCallResult(parseResponse(callParam));
			return 0 ;
		}
		if (sci.equals("UserResourceQueryDetail.ABMWH@027.ctnbc-bon.net")
				|| sci.equals("UserResourceQueryDetail.ABMHB@027.ctnbc-bon.net")
				|| sci.equals("UserResourceQueryDetail.ABM@027.ctnbc-bon.net")) {
			callParam.getAsynHandler().onCallResult(parseResponse(callParam));
		}
		if(sci.equals("RatableAuth.HSS@027.ctnbc-bon.net")){//预后判断
//			BusinessRecordCacheManager.getInstance().add(callParam);
			if(webService == WEBSERVICER && isHbFlag.equals("1")) {
				logger.info("===========进入webservice==============="+sb);
				String resp = StringEscapeUtils.unescapeXml(sendWebService(callParam, sb));
				logger.info("===========发送CCA==============="+resp);
				sendDCCCCRToOutNet(callParam, resp);
				
			}else {
				if(isHbFlag.equals("1") && homeAreaCode.equals("1001")){
					this.sendReqMsg(callParam, sb.toString() ,"2" ,"UserResourceQueryDetail.ABMWH@027.ctnbc-bon.net");
				} else if(isHbFlag.equals("1") && !homeAreaCode.equals("1001")){
					this.sendReqMsg(callParam, sb.toString() ,"2" ,"UserResourceQueryDetail.ABMHB@027.ctnbc-bon.net");
				}else{
					this.sendReqMsg(callParam, sb.toString() ,"2" ,"UserResourceQueryDetail.ABM@027.ctnbc-bon.net");
				}
			}
		}
		return 0;
	}

	private void sendDCCCCRToOutNet(CallParam callParam, String resp) {
		try {
			XmlMessage ack = new XmlMessage(false);
			String  respStr = "<ServiceInformation>(.*)</ServiceInformation>";
			Pattern pattern = Pattern.compile(respStr);
			Matcher matcher = pattern.matcher(resp);
			String interceptRespStr = "";
			while (matcher.find()) {
				interceptRespStr = matcher.group(1);
			}
			resp = "<ServiceInformation>"+interceptRespStr+"</ServiceInformation>";
			resp = resp.replaceAll("ServiceInformation", "Service_Information");
			resp = resp.replaceAll("ServiceResultCode", "Result");
			resp = resp.replaceAll("ParaFieldResult", "Para_Field_Result");
			resp = resp.replaceAll("ProductOFFinfo", "Product_OFF_info");
			resp = resp.replaceAll("ProductOfferId", "Product_Offer_Id");
			resp = resp.replaceAll("ProdOfferInstanceId", "ProdOfferInstanceId");
			resp = resp.replaceAll("ServGroupQuery", "Serv_Group_Query");
			resp = resp.replaceAll("OfferType", "Offer-Type");
			resp = resp.replaceAll("AccNbr", "Acc_Nbr");
			resp = resp.replaceAll("RatableResourceID", "Ratable_Resource_ID");
			resp = resp.replaceAll("ServTypeId", "Serv_Type_Id");
			resp = resp.replaceAll("DestinationAttr", "DestinationAttr");
			resp = resp.replaceAll("UsageAmount", "Usage-Amount");
			resp = resp.replaceAll("UnitTypeId", "UnitType_Id");
			if(!resp.isEmpty()) {
				XmlMessage message = (XmlMessage)callParam.getRequest();
				String mid = message.getMID();
				ack.setMID(mid.substring(0, mid.length()-1));
				ack.setREPTAG(0);
				ack.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Long.valueOf(System.currentTimeMillis())));
				ack.setSIG(null);
				ack.setRC("0");
				ack.setDS("SUCCESS");
				ack.setDATA(resp);
				callParam.setRecvResponse(ack);
			}
			callParam.setRequest(callParam.getSendRequest());
			callParam.getAsynHandler().onCallResult(callParam);
			logger.info("===========发送cca结束===============");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    private static void sendDCCCCRToOutNet2(CallParam callParam, String resp)  {
        try {
            XmlMessage ack = new XmlMessage(false);
            JSONObject resp_json=JSONObject.parseObject(resp);
            Element serviceInformation = DocumentHelper.createElement("Service_Information");
            Element element = serviceInformation.addElement("Result");
            element.setText(resp_json.getString("resultCode"));
            element = serviceInformation.addElement("Para_Field_Result");
            element.setText(resp_json.getString("resultMsg"));
            JSONArray offerInstInfoList=resp_json.getJSONArray("DetailOfferInstInfo");
            if(offerInstInfoList != null){
                for (int i=0;i<offerInstInfoList.size();i++){
                    JSONObject offer=offerInstInfoList.getJSONObject(i);
                    serviceInformation.addElement("Product_OFF_info");//添加空节点
                    List<Element> list =serviceInformation.elements("Product_OFF_info");
                    Element offerInstInfo = list.get(i);
                    offerInstInfo.addElement("Product_Offer_Id").setText(offer.getString("offerId"));
                    offerInstInfo.addElement("ProdOfferInstanceId").setText(offer.getString("offerInstId"));
                    JSONArray AccuQryListS=offer.getJSONArray("AccuQryUserList");
                    for (int j=0;j<AccuQryListS.size();j++){
                        offerInstInfo.addElement("Serv_Group_Query");//添加空节点
                        JSONObject AccuQry=AccuQryListS.getJSONObject(j);
                        List<Element> list2= offerInstInfo.elements("Serv_Group_Query");
                        Element AccuQryList= list2.get(j);
                        AccuQryList.addElement("Acc_Nbr").setText(AccuQry.getString("accNbr"));
                        AccuQryList.addElement("Serv_Type_Id").setText(AccuQry.getString("servTypeId"));
                        AccuQryList.addElement("DestinationAttr").setText(AccuQry.getString("destinationAttr"));
                        AccuQryList.addElement("Ratable_Resource_ID").setText(AccuQry.getString("accuTypeId"));
                        AccuQryList.addElement("Usage-Amount").setText(AccuQry.getString("usageAmount"));
                        AccuQryList.addElement("UnitType_Id").setText(AccuQry.getString("unitTypeId"));
                    }
                }
            }

            logger.info("==================返回CCA  serviceInformation=============="+serviceInformation.asXML());
            if(!resp.isEmpty()) {
                XmlMessage message = (XmlMessage)callParam.getRequest();
                String mid = message.getMID();
                ack.setMID(mid.substring(0, mid.length()-1));
                ack.setREPTAG(0);
                ack.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Long.valueOf(System.currentTimeMillis())));
                ack.setSIG(null);
                ack.setRC("0");
                ack.setDS("SUCCESS");
                ack.setDATA(serviceInformation.asXML());
                callParam.setRecvResponse(ack);
            }
            callParam.setRequest(callParam.getSendRequest());
            callParam.getAsynHandler().onCallResult(callParam);
            logger.info("===========发送cca结束===============");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	private String sendWebService(CallParam callParam, StringBuilder sb) {
		String resp = "";
		String url  = userResourceDetailConfigService.getValue("RATABLE_RESOURCE_QUERY_URL","");
		PostMethod post = new PostMethod(url);
		try {
			RequestEntity requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");
			post.setRequestEntity(requestEntity);
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5*1000);
			try {
				client.executeMethod(post);
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				logger.info("===========完成webservice==============="+resp);
				resp = post.getResponseBodyAsString();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return resp;
	}

    private String sendWebSevice2(CallParam callParam, StringBuilder sb) {
        String resp = "";
        String url  = userResourceDetailConfigService.getValue("RATABLE_RESOURCE_QUERY_URLjf3","");
        PostMethod post = new PostMethod(url);
        logger.info("=========== http请求开始===============url:"+url);
        try {
            RequestEntity requestEntity = new StringRequestEntity(jsonObject.toString(), "application/json", "UTF-8");
            post.setRequestEntity(requestEntity);
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5*1000);
            try {
                client.executeMethod(post);
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                logger.info("===========完成http请求 ==============="+resp);
                resp = post.getResponseBodyAsString();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resp;
    }

	private void getDCC(String accNbr, String billingCycle, String destinationAttr, StringBuilder sb) {
		sb.append("<Service_Information>").append("<Bill_Information>");
		if(accNbr != null && !"".equals(accNbr)){
			sb.append("<Acc_Nbr>").append(accNbr).append("</Acc_Nbr>");
		}
		if(billingCycle != null && !"".equals(billingCycle)){
			sb.append("<Billing_Cycle>").append(billingCycle).append("</Billing_Cycle>");
		}
		if(destinationAttr != null && !"".equals(destinationAttr)){
			sb.append("<DestinationAttr>").append(destinationAttr).append("</DestinationAttr>");
		}
		
		if(!"".equals(QUERY_FLAG)){
			sb.append("<Query_Flag>").append(QUERY_FLAG).append("</Query_Flag>");
		}
		if(PRODUCT_OFFER_INSTANCE_ID != null && !"".equals(PRODUCT_OFFER_INSTANCE_ID)){
			sb.append("<ProdOfferInstanceId>").append(PRODUCT_OFFER_INSTANCE_ID).append("</ProdOfferInstanceId>");
		}
		sb.append("</Bill_Information>").append("</Service_Information>");
	}

	private void getWebServiceCCR(String accNbr, String billingCycle, String destinationAttr, StringBuilder sb) {
		sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.hquery.ailk.com/\">");
		sb.append("<soapenv:Header/>");
		sb.append("<soapenv:Body>");
		sb.append("<ser1:queryRatableDetail xmlns:ser1=\"http://server.ratable.asiainfo.com/\">");
		sb.append("<param><![CDATA[  ");
		sb.append("<query from='" +212+ "'>");
		if(accNbr != null && !"".equals(accNbr)){ 
			sb.append("<AccNbr>" + accNbr + "</AccNbr>");
		}
		if(destinationAttr != null && !"".equals(destinationAttr)){
			sb.append("<DestinationAttr>" + destinationAttr + "</DestinationAttr>");
		}
		if(billingCycle != null && !"".equals(billingCycle)){
			sb.append("<BillingCycle>" + billingCycle + "</BillingCycle>");
		}
		if(PRODUCT_OFFER_INSTANCE_ID != null && !"".equals(PRODUCT_OFFER_INSTANCE_ID)){
			sb.append("<ProdOfferInstanceId>" + PRODUCT_OFFER_INSTANCE_ID + "</ProdOfferInstanceId>");
		}
		if(!"".equals(QUERY_FLAG)){
			sb.append("<QueryFlag>" + QUERY_FLAG + "</QueryFlag>");
		}
		sb.append("</query>");
		sb.append("]]>");
		sb.append("</param>");
		sb.append("</ser1:queryRatableDetail>");
		sb.append("</soapenv:Body>");
		sb.append("</soapenv:Envelope>");
	}

	@Override
	public int process(CallParam callParam) {
		jf3_flag = userResourceConfigService.getValue("jf3_flag","");
		logger.info("===========7777777777===============" );
		XmlMessage request = (XmlMessage) callParam.getRequest();
		AVP avp = null;
		String accNbr = "";
		String destinationAttr = "";
		String billingCycle = "";
		Document root;
		try {
			root = DocumentHelper.parseText(request.getDATA());
			org.dom4j.Node node = root.selectSingleNode("//Service_Information/Bill_Information/Acc_Nbr");
			if (node != null) {
				accNbr = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/Billing_Cycle");
			if (node != null) {
				billingCycle = node.getStringValue();
			}
			
			node = root.selectSingleNode("//Service_Information/Bill_Information/DestinationAttr");
			if (node != null) {
				destinationAttr = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/DestinationAttr");
			if (node != null) {
				destinationAttr = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/ProdOfferInstanceId");
			if (node != null) {
				PRODUCT_OFFER_INSTANCE_ID = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/Query_Flag");
			if (node != null) {
				QUERY_FLAG = node.getStringValue();
			}
			node = root.selectSingleNode("//Service_Information/Bill_Information/QueryType");
		} catch (DocumentException e) {
			e.printStackTrace();
		}
        JSONObject operAttrStruct=new JSONObject();
        operAttrStruct.put("operServiceId", DateUtil.dateTimeToStr(new Date())+(int)(Math.random()*1000000) );
        operAttrStruct.put("lanId","8420000");
        operAttrStruct.put("operPost","1");
        operAttrStruct.put("operOrgId","1");
        operAttrStruct.put("staffId","1");
        operAttrStruct.put("operTime",DateUtil.dateTimeToStr(new Date()));
        jsonObject.put("destinationAttr",destinationAttr);
        jsonObject.put("operAttrStruct",operAttrStruct);
        jsonObject.put("accNbr",accNbr);
        jsonObject.put("queryFlag",QUERY_FLAG);
        jsonObject.put("billingCycle",billingCycle);
        jsonObject.put("offerInstId",PRODUCT_OFFER_INSTANCE_ID);
		StringBuilder sb = new StringBuilder();
		sb.append("<Service_Information>")
			.append("<Bill_Information>") ;

		if(accNbr != null && !"".equals(accNbr)){
			sb.append("<Acc_Nbr>").append(accNbr).append("</Acc_Nbr>");
		}
		if(billingCycle != null && !"".equals(billingCycle)){
			sb.append("<Billing_Cycle>").append(billingCycle).append("</Billing_Cycle>");
		}
		if(destinationAttr != null && !"".equals(destinationAttr)){
			sb.append("<DestinationAttr>").append(destinationAttr).append("</DestinationAttr>");
		}
		sb.append("</Bill_Information>")
			.append("</Service_Information>");
        String jf3_ratable_flag = userResourceConfigService.getValue("jf3_ratable_flag","");
        logger.info("===========jf3_ratable_flag==============="+jf3_ratable_flag );
		if( "1".equals(jf3_ratable_flag)) {
            logger.info("===========进入新流程===============");
			StringBuilder sb2 = new StringBuilder();
			getWebServiceCCR(accNbr, billingCycle, destinationAttr, sb2);
			logger.info("===========进入webservice==============="+sb2);
			String resp = StringEscapeUtils.unescapeXml(sendWebSevice2(callParam, sb2));
			logger.info("===========发送CCA==============="+resp);
			sendDCCCCRToOutNet2(callParam, resp);
			return 0;
		}
        logger.info("===========进入旧的流程===============");
		this.sendReqMsg(callParam, sb.toString() ,"1" ,"RatableAuth.HSS@027.ctnbc-bon.net");
//		BusinessRecordCacheManager.getInstance().add(callParam1);
//		SpringContext.getInstance().getOuterDBDataService().saveToDB(SGWDataStoreService.convertCallParamToBusinessRecord((CallParam) oneCallParam));
		
		return 0;
	}

	public static void main(String [] srg){
	    String resp="{\"resultMsg\":\"调用成功\",\"resultCode\":\"0\",\"DetailOfferInstInfo\":[{\"offerInstId\":\"11219141588\",\"offerId\":\"250141788\",\"AccuQryUserList\":[{\"accNbr\":\"18107276401\",\"unitTypeId\":\"1\",\"servTypeId\":\"2\",\"destinationAttr\":\"2\",\"usageAmount\":\"0\",\"accuTypeId\":\"131100\"},{\"accNbr\":\"18107276401\",\"unitTypeId\":\"3\",\"servTypeId\":\"2\",\"destinationAttr\":\"2\",\"usageAmount\":\"0\",\"accuTypeId\":\"331101\"},{\"accNbr\":\"15391568847\",\"unitTypeId\":\"1\",\"servTypeId\":\"2\",\"destinationAttr\":\"2\",\"usageAmount\":\"0\",\"accuTypeId\":\"131100\"},{\"accNbr\":\"15391568847\",\"unitTypeId\":\"3\",\"servTypeId\":\"2\",\"destinationAttr\":\"2\",\"usageAmount\":\"0\",\"accuTypeId\":\"331101\"},{\"accNbr\":\"18107278401\",\"unitTypeId\":\"1\",\"servTypeId\":\"2\",\"destinationAttr\":\"2\",\"usageAmount\":\"0\",\"accuTypeId\":\"131100\"},{\"accNbr\":\"18107278401\",\"unitTypeId\":\"3\",\"servTypeId\":\"2\",\"destinationAttr\":\"2\",\"usageAmount\":\"0\",\"accuTypeId\":\"331101\"}]}]}";
        XmlMessage ack = new XmlMessage(false);
        JSONObject resp_json=JSONObject.parseObject(resp);
        Element serviceInformation = DocumentHelper.createElement("Service_Information");
        Element element = serviceInformation.addElement("Result");
        element.setText(resp_json.getString("resultCode"));
        element = serviceInformation.addElement("Para_Field_Result");
        element.setText(resp_json.getString("resultMsg"));
        JSONArray offerInstInfoList=resp_json.getJSONArray("DetailOfferInstInfo");
        for (int i=0;i<offerInstInfoList.size();i++){
            JSONObject offer=offerInstInfoList.getJSONObject(i);
            serviceInformation.addElement("Product_OFF_info");//添加空节点
            List<Element> list =serviceInformation.elements("Product_OFF_info");
            Element offerInstInfo = list.get(i);
            offerInstInfo.addElement("Product_Offer_Id").setText(offer.getString("offerId"));
            offerInstInfo.addElement("ProdOfferInstanceId").setText(offer.getString("offerInstId"));
            JSONArray AccuQryListS=offer.getJSONArray("AccuQryUserList");
            for (int j=0;j<AccuQryListS.size();j++){
                offerInstInfo.addElement("Serv_Group_Query");//添加空节点
                JSONObject AccuQry=AccuQryListS.getJSONObject(j);
                List<Element> list2= offerInstInfo.elements("Serv_Group_Query");
                Element AccuQryList= list2.get(j);
                AccuQryList.addElement("Acc_Nbr").setText(AccuQry.getString("accNbr"));
                AccuQryList.addElement("Serv_Type_Id").setText(AccuQry.getString("servTypeId"));
                AccuQryList.addElement("DestinationAttr").setText(AccuQry.getString("destinationAttr"));
                AccuQryList.addElement("Ratable_Resource_ID").setText(AccuQry.getString("accuTypeId"));
                AccuQryList.addElement("Usage-Amount").setText(AccuQry.getString("usageAmount"));
                AccuQryList.addElement("UnitType_Id").setText(AccuQry.getString("unitTypeId"));
            }
        }
    }


}
